<template>
  <div>
    <!-- 属性配置 -->
    <el-button @click="addAttribute" type="success" size="mini">添加属性</el-button>
    <el-table :data="attributes" border style="width: 100%">
<!--      <el-table-column prop="attributeName" label="属性名称"></el-table-column>-->
      <el-table-column label="属性值">
        <template v-slot="{ row }">
          <el-input v-model="row.attributeValues" placeholder="用竖线(|)分隔，如：蓝色|白色|灰色"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template v-slot="{ $index }">
          <el-button size="mini" type="danger" @click="removeAttribute($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- SKU列表 -->
    <el-button @click="handleMakeSku" size="mini" style="margin-top: 20px" type="warning">生成SKU</el-button>
    <el-button @click="batchSetVisible = true" size="mini">批量设置</el-button>
    <el-table :data="skus" border style="width: 100%;" @cell-change="handleSkuChange" >
      <el-table-column prop="spec_key" label="规格键名" header-align="center"></el-table-column>
      <el-table-column prop="spec_name" label="规格名称" header-align="center"></el-table-column>
      <el-table-column prop="store_count" label="库存" header-align="center">
        <template v-slot="{ row }">
          <el-input size="mini" v-model.number="row.store_count" @input="handleSkuChange(row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="销售价格" header-align="center">
        <template v-slot="{ row }">
          <el-input-number v-model="row.price" size="mini" controls-position="right" :precision="2" :step="0.01" :min="0" @change="handleSkuChange(row)"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="cost_price" label="成本价" header-align="center">
        <template v-slot="{ row }">
          <el-input-number v-model="row.cost_price" size="mini" controls-position="right" :precision="2" :step="0.01" :min="0" @change="handleSkuChange(row)"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="market_price" label="市场价" header-align="center">
        <template v-slot="{ row }">
          <el-input-number v-model="row.market_price" size="mini" controls-position="right" :precision="2" :step="0.01" :min="0" @change="handleSkuChange(row)"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" header-align="center">
        <template v-slot="{ $index }">
          <el-button size="mini" type="danger" @click="removeSku($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 批量设置 -->
<!--    <el-button @click="batchSetVisible = true">批量设置</el-button>-->
    <el-dialog title="批量设置" :visible.sync="batchSetVisible">
      <el-form :model="batchForm">
        <el-form-item label="价格" :label-width="formLabelWidth">
          <el-input v-model="batchForm.price"></el-input>
        </el-form-item>
        <el-form-item label="库存" :label-width="formLabelWidth">
          <el-input v-model.number="batchForm.store_count"></el-input>
        </el-form-item>
        <el-form-item label="成本价" :label-width="formLabelWidth">
          <el-input v-model="batchForm.cost_price" ></el-input>
        </el-form-item>
        <el-form-item label="市场价" :label-width="formLabelWidth">
          <el-input v-model="batchForm.market_price"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="batchSetVisible = false">取消</el-button>
        <el-button type="primary" @click="applyBatchSet">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    initialSkus: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      attributes: [], // 存储属性及其值
      skus: [], // 存储生成的SKU列表
      batchSetVisible: false, // 控制批量设置对话框显示状态
      batchForm: {
        price: '',
        store_count: null,
        cost_price: null,
        market_price: null
      },
      formLabelWidth: '80px'
    }
  },
  watch: {
    skus: {
      deep: true,
      handler(newValue) {
        this.$emit('sku-updated', newValue)
      }
    }
  },
  created() {
    // 初始化时从props中获取已有SKU数据，并解析出属性和SKU列表
    if (this.initialSkus.length > 0) {
      this.parseInitialSkus(this.initialSkus)
    }
  },
  methods: {
    addAttribute() {
      this.attributes.push({ attributeName: '', attributeValues: '' })
    },
    removeAttribute(index) {
      this.attributes.splice(index, 1)
    },
    handleMakeSku() {
      console.log('handleMakeSku')
      if (this.attributes.length === 0) {
        this.$message.error('请先添加属性')
        return
      }

      if (this.skus.length > 0) {
        this.$confirm('已存在SKU，是否覆盖？', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.generateSkus()
        }).catch(() => {
          // 取消操作
        })
      } else {
        this.generateSkus()
      }
    },
    generateSkus() {
      // 清空现有的SKU列表
      this.skus = []

      // 获取所有属性值并创建所有可能的组合
      const combinations = this.createCombinations(this.attributes)

      // 根据组合生成SKUs
      combinations.forEach(combination => {
        const specKey = combination.join('_')
        const specName = combination.join(';')

        this.skus.push({
          spec_key: specKey,
          spec_name: specName,
          store_count: 0,
          price: 0.00,
          cost_price: 0.00,
          market_price: 0.00
        })
      })
    },
    createCombinations(attributes) {
      const valueLists = attributes.map(attr => attr.attributeValues.split('|').map(val => val.trim()))
      const result = []

      function combine(tempArray, index) {
        if (index === valueLists.length) {
          result.push(tempArray.slice())
          return
        }
        for (let i = 0; i < valueLists[index].length; i++) {
          tempArray[index] = valueLists[index][i]
          combine(tempArray, index + 1)
        }
      }

      combine([], 0)
      return result
    },
    removeSku(index) {
      this.skus.splice(index, 1)
    },
    applyBatchSet() {
      const { price, store_count, cost_price, market_price } = this.batchForm

      // 更新所有SKU对应的字段
      this.skus.forEach(sku => {
        if (price !== '') sku.price = parseFloat(price)
        if (store_count !== null) sku.store_count = store_count
        if (cost_price !== null) sku.cost_price = cost_price
        if (market_price !== null) sku.market_price = market_price
      })

      // 关闭对话框
      this.batchSetVisible = false
    },
    handleSkuChange(row) {
      // 触发更新事件，将最新的SKU数据传递给父组件
      this.$emit('sku-updated', this.skus)
    },
    parseInitialSkus(initialSkus) {
      // 创建一个映射来保存每个属性名称及其对应的值集合
      const attributeMap = new Map()

      // 遍历初始SKU数据，提取所有属性和对应的值
      initialSkus.forEach(sku => {
        // 提取属性名称
        const [color, size] = sku.spec_key.split('_')

        // 提取属性值
        const values = sku.spec_name.split(';')

        // 添加属性值到集合中
        values.forEach(value => {
          if (!attributeMap.has(color)) {
            attributeMap.set(color, [])
          }
          if (!attributeMap.has(size)) {
            attributeMap.set(size, [])
          }

          attributeMap.get(color).push(value.trim())
          attributeMap.get(size).push(value.trim())
        })
      })
      // 设置初始SKU列表
      this.skus = initialSkus
      // 构建属性对象数组，并确保每个属性值是按规则分隔的字符串,fixme 这里有问题，不是和生成一致的
      /*  this.attributes = Array.from(attributeMap.entries()).map(([key, values]) => ({
         attributeName: key,
         // 将数组转换为字符串，使用' | '作为分隔符
         attributeValues: values.sort().join(' | ')
       })) */
    }
  }
}
</script>
